//
//  DSHomeController.m
//  DSJY
//
//  Created by 冯华强 on 16/9/23.
//  Copyright © 2016年 dsjy. All rights reserved.
//  首页

#import "DSHomeController.h"
#import "DSBuyUnitController.h"
#import "MTNavigationController.h"
#import "DSLeaderboardController.h"
#import "DSLearnScoreController.h"
#import "DSUnitExerciseController.h"
#import "DSLoginController.h"
#import "DSRegisgerController.h"
#import "MTConst.h"
#import "UIStoryboard+Extension.h"
#import "DSUnitListController.h"
#import "DSHomeViewModel.h"
#import "DSCourseCell.h"
#import "DSCourse.h"
#import "UIBarButtonItem+Extension.h"
#import "UIColor+Extension.h"
#import "DSAccountViewModel.h"
#import "DSAccount.h"
#import "UIWindow+Extension.h"
#import "NSString+Extension.h"
#import "DSOrderListController.h"
#import "MBProgressHUD+MJ.h"
#import "DSLoginViewModel.h"
#import "DSSettingViewController.h"

@interface DSHomeController () <UIActionSheetDelegate>
//首页VM
@property (nonatomic, strong) DSHomeViewModel *homeVM;
//登录VM
@property (nonatomic, strong) DSLoginViewModel *loginVM;
@end

@implementation DSHomeController

#pragma mark - 懒加载
- (DSHomeViewModel *)homeVM
{
    if (_homeVM == nil) {
        _homeVM = [[DSHomeViewModel alloc] init];
    }
    return _homeVM;
}

- (DSLoginViewModel *)loginVM
{
    if (_loginVM == nil) {
        _loginVM = [[DSLoginViewModel alloc] init];
    }
    return _loginVM;
}

#pragma mark - 系统回调
- (void)viewDidLoad
{
    [super viewDidLoad];
    
    //设置导航栏左侧
    [self setupLeftBarItem];
    
    //设置右边的BarItem
    [self setupRightBarItem];
    
    //监听通知
    [self setupNotifications];
    
    //绑定事件
    [self bindEvent];
    
    //hq_test
    MTLog(@"============%@", [DSAccountViewModel sharedAccount].account.stuId);
}

- (void)viewWillAppear:(BOOL)animated
{
    [super viewWillAppear:animated];
    
    //刷新首页
    [self checkNetWorkWithRefreshType:YQRefreshTypeHeader];
}

- (void)dealloc
{
    [MTNotificationCenter removeObserver:self];
}

#pragma mark - 设置UI
- (void)setupLeftBarItem
{
    NSMutableArray<UIBarButtonItem *> *items = [NSMutableArray<UIBarButtonItem *> array];
    //空白间隙的距离
    UIBarButtonItem *negativeSpacer = [UIBarButtonItem itemNegativeSpacer];
    negativeSpacer.width = -5;
    [items addObject:negativeSpacer];

    //大思英语logo
    UIBarButtonItem *logoItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"ds_logo"] style:UIBarButtonItemStylePlain target:nil action:nil];
    logoItem.enabled = NO;
    [items addObject:logoItem];
    
    DSAccount *account = [DSAccountViewModel sharedAccount].account;
    if (account.stuId != nil) {
        
        //排行榜
        UIBarButtonItem *leaderItem = [UIBarButtonItem itemWithTarget:self action:@selector(leaderItemClick) image:@"heros" title:nil];
//        UIBarButtonItem *leaderItem = [[UIBarButtonItem alloc] initWithImage:[UIImage imageNamed:@"heros"] style:UIBarButtonItemStylePlain target:self action:@selector(leaderItemClick)];
        [items addObject:leaderItem];
        
        //学习记录
        UIBarButtonItem *sourceItem = [UIBarButtonItem itemWithTarget:self action:@selector(sourceItemClick) image:@"xxjl" title:nil];
        [items addObject:sourceItem];
        
        //最近播放
        UIBarButtonItem *recentItem = [UIBarButtonItem itemWithTarget:self action:@selector(recentItemClick) image:@"learnnow" title:nil];
        [items addObject:recentItem];
        
        //设置
        UIBarButtonItem *settingItem = [UIBarButtonItem itemWithTarget:self action:@selector(settingItemClick) image:@"nav_setting_btn" title:nil];
        [items addObject:settingItem];

        
//        //订单
//        UIBarButtonItem *orderItem = [UIBarButtonItem itemWithTarget:self action:@selector(orderItemClick) image:@"nav_order" title:nil];
//        [items addObject:orderItem];
    
        //我的用户信息
        NSString *meTitle = [NSString stringWithFormat:@"欢迎您! %@", account.name];
        UIBarButtonItem *meItem = [UIBarButtonItem itemWithTarget:nil action:nil title:meTitle titleColor:[UIColor color333333] font:[UIFont systemFontOfSize:18]];
        [items addObject:meItem];
        
        //分割线
        UIBarButtonItem *lineItem = [UIBarButtonItem itemWithTarget:nil action:nil title:@"|" titleColor:[UIColor color333333] font:[UIFont systemFontOfSize:18]];
        [items addObject:lineItem];
        
        //登录按钮
        UIBarButtonItem *meOutItem = [UIBarButtonItem itemWithTarget:self action:@selector(meOutItemClick) title:@"退出" titleColor:[UIColor color333333] font:[UIFont systemFontOfSize:18]];
        [items addObject:meOutItem];
    }
    
    self.navigationItem.leftBarButtonItems = items;
}

- (void)setupRightBarItem
{
    NSMutableArray<UIBarButtonItem *> *items = [NSMutableArray<UIBarButtonItem *> array];
    
    //电话
    UIBarButtonItem *phoneItem = [UIBarButtonItem itemWithTarget:nil action:nil image:@"order_phone" title:@"020-87579153" titleColor:[UIColor color333333]];
    phoneItem.enabled = NO;
    [items addObject:phoneItem];
    
    DSAccount *account = [DSAccountViewModel sharedAccount].account;
    
    if (account.stuId == nil) {
        //游客登录按钮
        UIBarButtonItem *visitorsLoginItem = [UIBarButtonItem itemWithTarget:self action:@selector(visitorsLoginItemClick) title:@" 游客登录 " titleColor:[UIColor color333333] font:[UIFont systemFontOfSize:18]];
        [items addObject:visitorsLoginItem];
        
        //分割线
        UIBarButtonItem *visitorsLineItem = [UIBarButtonItem itemWithTarget:nil action:nil title:@"|" titleColor:[UIColor color333333] font:[UIFont systemFontOfSize:18]];
        [items addObject:visitorsLineItem];
        
        //登录按钮
        UIBarButtonItem *loginItem = [UIBarButtonItem itemWithTarget:self action:@selector(loginItemClick) title:@" 登录 " titleColor:[UIColor color333333] font:[UIFont systemFontOfSize:18]];
        [items addObject:loginItem];
        
        //分割线
        UIBarButtonItem *lineItem = [UIBarButtonItem itemWithTarget:nil action:nil title:@"|" titleColor:[UIColor color333333] font:[UIFont systemFontOfSize:18]];
        [items addObject:lineItem];
        
        //注册按钮
        UIBarButtonItem *regisgerItem = [UIBarButtonItem itemWithTarget:self action:@selector(regisgerItemClick) title:@" 注册 " titleColor:[UIColor color333333] font:[UIFont systemFontOfSize:18]];
        [items addObject:regisgerItem];
    }
    
    self.navigationItem.rightBarButtonItems = items;
}

- (void)setupNotifications
{
    [MTNotificationCenter addObserver:self selector:@selector(refreshUser) name:DSLoginRegisgerSuccessNote object:nil];
}

#pragma mark - 设置事件
- (void)bindEvent
{
    @weakify(self);
    //如果验证通过，调用命令信号
    [self.homeVM.requestCommand.executionSignals.switchToLatest subscribeNext:^(id x) {
        @strongify(self);
        [self reloadDataWithCollectionView:self.collectionView currentPage:self.homeVM.pageNum totalPage:self.homeVM.response.total_page];
    }];
    
    //IAP支付成功，刷新列表
    [[[MTNotificationCenter rac_addObserverForName:DSIAPSuccessDidRefreshListNote object:nil] takeUntil:self.rac_willDeallocSignal] subscribeNext:^(NSNotification *noti) {
        @strongify(self);
        [self checkNetWorkWithRefreshType:YQRefreshTypeHeader];
    }];
    
    //有网络
    [self.networkWiFiWWANSignal subscribeNext:^(RACTuple *tuple) {
        @strongify(self);
        // 执行请求
        [self.homeVM.requestCommand execute:tuple[0]];
    }];
    
    //无网络
    [self.networkUnknownNotReachableSignal subscribeNext:^(id x) {
        @strongify(self);
        [self showEmptyHUDWithView:self.collectionView];
    }];
    
    //一开始加载
    if (YQAFNetworkReachabilityTool.requestBeforeJudgeConnect){
        [self.homeVM.requestCommand execute:@(YQRefreshTypeHeader)];
    }else{
        [self showEmptyHUDWithView:self.collectionView];
    }
}

//排行榜
- (void)leaderItemClick
{
    DSLeaderboardController *leaderVC = (DSLeaderboardController *)[UIStoryboard initialVCWithName:@"DSLeaderboardController"];
    leaderVC.title = @"排行榜";
    MTNavigationController *navVC = [[MTNavigationController alloc] initWithRootViewController:leaderVC];
    [self presentViewController:navVC animated:YES completion:nil];
}

//我的学习成绩
- (void)sourceItemClick
{
    DSLearnScoreController *scoreVC = (DSLearnScoreController *)[UIStoryboard initialVCWithName:@"DSLearnScoreController"];
    scoreVC.title = @"学习记录";
    MTNavigationController *navVC = [[MTNavigationController alloc] initWithRootViewController:scoreVC];
    [self presentViewController:navVC animated:YES completion:nil];
}

//最近学习播放
- (void)recentItemClick
{
    //打开最近学习
    DSUnitExerciseController *unitExerciseVC = (DSUnitExerciseController *)[UIStoryboard initialVCWithName:@"DSUnitExerciseController"];
    unitExerciseVC.title = @"最近学习";
    if (self.homeVM.courseList.count != 0) {
        unitExerciseVC.course = self.homeVM.courseList.firstObject;
    }
    MTNavigationController *navVC = [[MTNavigationController alloc] initWithRootViewController:unitExerciseVC];
//    navVC.autorotate = NO; //不允许旋转屏幕
    [self presentViewController:navVC animated:YES completion:nil];
}

//设置
- (void)settingItemClick
{
    DSSettingViewController *settingVC = [[DSSettingViewController alloc] init];
    settingVC.title = @"设置";
    MTNavigationController *navVC = [[MTNavigationController alloc] initWithRootViewController:settingVC];
    [self presentViewController:navVC animated:YES completion:nil];
}

//- (void)orderItemClick
//{
//    DSOrderListController *orderListVC = (DSOrderListController *)[UIStoryboard initialVCWithName:@"DSOrderListController"];
//    orderListVC.title = @"订单";
//    MTNavigationController *navVC = [[MTNavigationController alloc] initWithRootViewController:orderListVC];
//    [self presentViewController:navVC animated:YES completion:nil];
//}

//游客登录
- (void)visitorsLoginItemClick
{
    //游客登录
    [self.loginVM.visitorsLoginCommand execute:nil];
}

//登录
- (void)loginItemClick
{
    DSLoginController *loginVC = (DSLoginController *)[UIStoryboard initialVCWithName:@"DSLoginController"];
    loginVC.title = @"登录";
    loginVC.showBackItem = YES;
    MTNavigationController *navVC = [[MTNavigationController alloc] initWithRootViewController:loginVC];
    [self presentViewController:navVC animated:YES completion:nil];
}

//注册
- (void)regisgerItemClick
{
    DSRegisgerController *regisgerVC = (DSRegisgerController *)[UIStoryboard initialVCWithName:@"DSRegisgerController"];
    regisgerVC.title = @"注册";
    MTNavigationController *navVC = [[MTNavigationController alloc] initWithRootViewController:regisgerVC];
    [self presentViewController:navVC animated:YES completion:nil];
}

- (void)meOutItemClick
{
    UIActionSheet *sheet = [[UIActionSheet alloc] initWithTitle:@"是否退出登录？" delegate:self cancelButtonTitle:nil destructiveButtonTitle:@"确定" otherButtonTitles:@"取消", nil];
    [sheet showInView:self.view];
}

//刷新用户数据
- (void)refreshUser
{
    MTLog(@"已登录-------------------------------------------");
    //登录了，重新加载左右两侧导航item
    //进入的是首页才登录的时候
//    [self setupLeftBarItem];
//    [self setupRightBarItem];
//    
//    //重新加载数据
//    [self checkNetWorkWithRefreshType:YQRefreshTypeHeader];
    
    //进入的是两个选择登录的时候
    [UIWindow switchRootVCToAppDelegateWin];
}

#pragma mark - 
- (void)actionSheet:(UIActionSheet *)actionSheet clickedButtonAtIndex:(NSInteger)buttonIndex
{
    if (buttonIndex == 0) {
        //清除登录信息
        [DSAccountViewModel sharedAccount].account = nil;
        [[DSAccountViewModel sharedAccount] write];
        
        //刷新用户数据
        dispatch_after(dispatch_time(DISPATCH_TIME_NOW, (int64_t)(0.1 * NSEC_PER_SEC)), dispatch_get_main_queue(), ^{
            [self refreshUser];
        });
    }
}

#pragma mark <UICollectionViewDataSource>
- (NSInteger)collectionView:(UICollectionView *)collectionView numberOfItemsInSection:(NSInteger)section {
    
    //数据一刷新就会调用这个方法，所以放在这里比较合适
    //    [UIScreen mainScreen].bounds.size 或者 CGSizeMake(self.collectionView.width, 0);都可以
    [self viewWillTransitionToSize:[UIScreen mainScreen].bounds.size];
    return self.homeVM.courseList.count;
}

- (UICollectionViewCell *)collectionView:(UICollectionView *)collectionView cellForItemAtIndexPath:(NSIndexPath *)indexPath {
    DSCourseCell *cell = [collectionView dequeueReusableCellWithReuseIdentifier:courseReuseIdentifier forIndexPath:indexPath];
    cell.course = self.homeVM.courseList[indexPath.item];
    return cell;
}

#pragma mark <UICollectionViewDelegate>
- (void)collectionView:(UICollectionView *)collectionView didSelectItemAtIndexPath:(NSIndexPath *)indexPath
{
//    DSCourse *course = self.homeVM.courseList[indexPath.item];
//    NSString *stuId = [DSAccountViewModel sharedAccount].account.stuId;
//    if([NSString isEmptyWithStr:stuId] && course.isfreeb){
//        //没有登录、开锁的
//        UIAlertController *alertController = [UIAlertController alertControllerWithTitle:nil message:@"请先注册登录或游客登录，登录后可以免费学习此课程!" preferredStyle:UIAlertControllerStyleAlert];
//        UIAlertAction *cancelAction = [UIAlertAction actionWithTitle:@"取消" style:UIAlertActionStyleCancel handler:nil];
//        UIAlertAction *submitAction = [UIAlertAction actionWithTitle:@"好的" style:UIAlertActionStyleDefault handler:^(UIAlertAction * _Nonnull action) {
//            //跳转登录控制器
//            [self loginItemClick];
//        }];
//        [alertController addAction:cancelAction];
//        [alertController addAction:submitAction];
//        
//        [self presentViewController:alertController animated:YES completion:nil];
//    }else if ([NSString isNotEmptyWithStr:stuId]) {
//        if (!course.iscloseb || isDeBug) {
//            //登录、开锁的
//            DSUnitListController *unitListVC = [[DSUnitListController alloc] init];
//            unitListVC.title = course.name;
//            unitListVC.course = course;
//            MTNavigationController *navVC = [[MTNavigationController alloc] initWithRootViewController:unitListVC];
//            [self presentViewController:navVC animated:YES completion:nil];
//        }else if(course.iscloseb && ![course.islinktobuy isEqualToString:@"0"]){  //加锁的，islinktobuy不等于0
//            [self toBuyUnitVC];
//        }else{
//            [MBProgressHUD showText:@"学习完上一课程即可开通!"];
//        }
//    }else {
//        //未解锁，需要购买的课程
//        [self toBuyUnitVC];
//    }
    
    DSCourse *course = self.homeVM.courseList[indexPath.item];
    DSUnitListController *unitListVC = [[DSUnitListController alloc] init];
    unitListVC.title = course.name;
    unitListVC.course = course;
    MTNavigationController *navVC = [[MTNavigationController alloc] initWithRootViewController:unitListVC];
    [self presentViewController:navVC animated:YES completion:nil];
}

//- (void)toBuyUnitVC
//{
//    DSBuyUnitController *buyUnitVC = [[DSBuyUnitController alloc] init];
//    buyUnitVC.title = @"课程介绍";
//    MTNavigationController *navVC = [[MTNavigationController alloc] initWithRootViewController:buyUnitVC];
//    [self presentViewController:navVC animated:YES completion:nil];
//}

@end
